package com.hspedu.hspliving.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hspedu.hspliving.commodity.entity.*;
import com.hspedu.hspliving.commodity.service.*;
import com.hspedu.hspliving.commodity.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.common.utils.PageUtils;
import com.hspedu.common.utils.Query;

import com.hspedu.hspliving.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存spu商品信息
     * 多表操作-事务控制
     * @param spuSaveVO
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //值拷贝
        BeanUtils.copyProperties(spuSaveVO,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        //1.add spu商品信息
        this.saveBaseSpuInfo(spuInfoEntity);
        //保存spu图片url信息
        List<String> decripts = spuSaveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //设置id为 spu基础信息添加后的id
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //判断 decripts 是否包含图片url
        if (decripts.size() == 0){
            //没有上传，使用默认图片url
            spuInfoDescEntity.setDecript("default.jpg");
        }else {
            //存在，进行遍历,多个图片url，使用,间隔
            spuInfoDescEntity.setDecript(String.join(",",decripts));
        }
        //2.保存 spuInfoDescEntity
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        //3.保存 spu 图片集
        spuImagesService.saveImages(spuInfoEntity.getId(),spuSaveVO.getImages());
        //4.保存spu对应基本属性[一个spu对应多个基本属性]
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        //遍历 baseAttrs
        List<ProductAttrValueEntity> productAttrValueEntitys = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValueEntity =
                    new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntity.setAttrSort(0);//默认排序值
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            //获取到 基本属性名称
            AttrEntity attr = attrService.getById(productAttrValueEntity.getAttrId());
            if (attr != null) {
                productAttrValueEntity.setAttrName(attr.getAttrName());
            }
            return productAttrValueEntity;
        }).collect(Collectors.toList());

        //执行添加
        productAttrValueService.saveProductAttr(productAttrValueEntitys);

        //5.保存sku基本信息
        List<Skus> skus = spuSaveVO.getSkus();
        if (skus != null && skus.size() > 0){
            skus.forEach(sku -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                //处理默认图片
                String defaultImg = "default.jpg";
                //json 会提交很多图片，如果是当前这个sku 的默认图片就先保存下url
                for (Images image :sku.getImages()) {
                    if (image.getDefaultImg() == 1){
                        //如果存在默认图片，替换url
                        defaultImg = image.getImgUrl();
                    }
                }
                //数据转换
                skuInfoEntity.setSaleCount(0L);//初始化销量为0
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setPrice(sku.getPrice());
                skuInfoEntity.setSkuName(sku.getSkuName());
                skuInfoEntity.setSkuTitle(sku.getSkuTitle());
                skuInfoEntity.setSkuSubtitle(sku.getSkuSubtitle());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //保存sku基本信息
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //6. 保存sku图片集信息-到commodity_sku_images
                //过滤 img-url为null的情况
                List<SkuImagesEntity> skuImagesEntitys = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    return skuImagesEntity;
                }).filter(img -> {
                    //过滤掉 img_url为空的值
                    return StringUtils.isNotBlank(img.getImgUrl());
                }).collect(Collectors.toList());

                //批量添加
                skuImagesService.saveBatch(skuImagesEntitys);

                //7.保存sku销售属性-list
                List<Attr> attrs = sku.getAttr();
                //遍历attrs,将数据封装到 SkuSaleAttrValueEntity
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntitys = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                    skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                    skuSaleAttrValueEntity.setAttrSort(0);//默认排序
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                //批量新增
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntitys);
            });

        }
    }

    /**
     * 保存spu 的基本信息到commodity_spu_info
     * @param spuInfoEntity
     */
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * spu管理界面-条件+分页检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        //1.检索条件key
        String key = (String)params.get("key");
        if (StringUtils.isNotBlank(key)){
            //key为id时精确查询，为名称时模糊查询
            wrapper.and(w -> {
                w.eq(SpuInfoEntity::getId,key).or().like(SpuInfoEntity::getSpuName,key);
            });
        }
        //2.检索条件-状态
        String status = (String)params.get("status");
        wrapper.eq(StringUtils.isNotBlank(status),SpuInfoEntity::getPublishStatus,status);
        //3.检索条件-品牌
        String brandId = (String) params.get("brandId");
        wrapper.eq(StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)
                ,SpuInfoEntity::getBrandId,brandId);
        //4.检索条件-分类id
        String catalogId = (String) params.get("catalogId");
        wrapper.eq(StringUtils.isNotBlank(catalogId) && !"0".equalsIgnoreCase(catalogId)
                ,SpuInfoEntity::getCatalogId,catalogId);

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * spu上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        this.baseMapper.updaSpuStatus(spuId,1);
    }

    /**
     * spu下架
     * @param spuId
     */
    @Override
    public void down(Long spuId) {
        this.baseMapper.updaSpuStatus(spuId,2);
    }


}
